/**
 * @file   SocketClientTTF001.java
 * @date   2012-11-13下午5:41:49
 * @author User
 */
package com.gzceb.zhgjj.socket;

import java.net.InetSocketAddress;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import com.gzceb.zhgjj.mina.SplatCodeFactory;
import com.gzceb.zhgjj.mina.TTF001.SendTTF001File;
import com.gzceb.zhgjj.util.PropertiesUtils;

/**
 * <p>TTF001 7661端口发送响应文件类。</p>
 *
 * @date   2012-11-13下午5:41:49 
 * @author liqing
 * @description 本端向中心7661端口发送响应文件。
 *              在处理完文件之后，才调用此类打开socket客户端发送文件
 */
public class SocketClientTTF001 {

	private static Log logger = LogFactory.getLog(SocketClientTTF001.class);
	
	public static boolean service(String fileName){
		//Create TCP/IP connection   
		NioSocketConnector connector = new NioSocketConnector();   
		boolean result;     
		try{
		//创建接受数据的过滤器   
		DefaultIoFilterChainBuilder chain = connector.getFilterChain(); 
		chain.addLast("mychain", new ProtocolCodecFilter(new SplatCodeFactory()));
		//服务器的消息处理器：一个SamplMinaServerHander对象   
		connector.setHandler(new SendTTF001File(fileName));   
		connector.setConnectTimeoutMillis(600000); //设置超时时间为10分钟
		connector.getSessionConfig().setWriteTimeout(600);
		
		logger.info("客户端开始连接中心服务器7661端口，准备发送文件。");
		//连接到服务器：   
		ConnectFuture cf = connector.connect(new InetSocketAddress(PropertiesUtils.getValue("ipAddr"),
																	Integer.parseInt(PropertiesUtils.getValue("port"))));
		
		logger.info("7661客户端完成文件传输，准备关闭。");
		//Wait for the connection attempt to be finished.   
		cf.awaitUninterruptibly();   
		cf.getSession().getCloseFuture().awaitUninterruptibly();   
		
		connector.dispose();
		result = true;
		}catch(Exception e){
			logger.error("7661客户端启动连接中出现异常。 \n" + e.getMessage());
			result = false;
		}

		return result;
	}
	
	public static void main(String[] args){
		SocketClientTTF001.service("LA9905912012032700010");
	}
}
